package com.hinata.hinataimageloader;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UploadHomeworkActivity extends AppCompatActivity {
    Button btnUploadImage;
    private static final String UP_HOMEWORK_URL = "http://172.27.35.2:8080/HiTeacher/homework/addHomework";
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");
    private static final String pic_key = "homeworkImages";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_homework);

        final Map<String, String> uploadHomeworkParams = new HashMap<>();
        uploadHomeworkParams.put("teacherId", "123456");
        uploadHomeworkParams.put("courseId", "1");
        uploadHomeworkParams.put("classId", "1");
        uploadHomeworkParams.put("studentId", "1504121860");
        uploadHomeworkParams.put("name", "lucy");
        uploadHomeworkParams.put("homeworkOrder", "2");

        final List<File> imagelist = new ArrayList<File>();
        File file1 = new File("/sdcard/Pictures/tuzi.png");
        File file2 = new File("/sdcard/Pictures/tuzi2.png");
        if (file1.exists())
            Log.w("joshua", "file exist");
        imagelist.add(file1);
        imagelist.add(file2);

        btnUploadImage = (Button) findViewById(R.id.btn_upload_image);
        btnUploadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.w("joshua", "test");
                sendMultipart(UP_HOMEWORK_URL, uploadHomeworkParams, pic_key, imagelist);
            }
        });
    }

    /**
     * 上传多张图片及参数
     *
     * @param reqUrl  URL地址
     * @param params  参数
     * @param pic_key 上传图片的关键字
     * @param files   图片路径
     */
    public void sendMultipart(String reqUrl, Map<String, String> params, String pic_key, List<File> files) {
        OkHttpClient client = new OkHttpClient();
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //遍历map中所有参数到builder
        if (params != null) {
            for (String key : params.keySet()) {
                multipartBodyBuilder.addFormDataPart(key, params.get(key));
            }
        }
        //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
        if (files != null) {
            for (File file : files) {
                multipartBodyBuilder.addFormDataPart(pic_key, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            }
        }

        Log.w("joshua", "test");

        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();

        Request request = new Request.Builder()
                .url(reqUrl)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.w("joshua", "请求上传作业失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.w("joshua", "请求上传作业成功");
                Log.w("joshua", response.body().string());
            }
        });


    }

}
